package cn.asura.otherChat.server;

import cn.asura.otherChat.thread.ServerThread;
import cn.asura.otherChat.util.ServerTool;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;

public class MyServer {
    // 最大用户连接数
    private static final int MAX_SOCKET_NUM = 10;

    // 套接字数组
    public static Socket[] sockets = new Socket[MAX_SOCKET_NUM];

    // 当前连接数
    public static int socketNum;

    // 初始化静态成员
    static {
        Arrays.fill(sockets, null);
        socketNum = 0;
    }

    public static void main(String[] args) {
        ServerSocket serverSocket;
        BufferedReader bufferedReader = null;

        try {
            // 初始化服务器，创建本地存储目录
            serverSocket = new ServerSocket(9090);
            ServerTool.createLocalStorage();
            System.out.println("等待客户端连接");

            while (socketNum < MAX_SOCKET_NUM) {
                // 等待连接
                sockets[socketNum] = serverSocket.accept();

                // 连接成功后获取用户名
                bufferedReader = new BufferedReader(new InputStreamReader(sockets[socketNum].getInputStream()));
                String name = bufferedReader.readLine();
                System.out.println(name + "上线了");
                ServerTool.shareMsg(socketNum, "服务器", name + "上线了");

                // 启动线程读取客户端发送的消息
                ServerThread serverThread = new ServerThread(socketNum, name);
                new Thread(serverThread).start();

                socketNum++;
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != bufferedReader) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
